package com.thfw.test.utils;

import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;

import androidx.loader.content.CursorLoader;

import java.lang.reflect.Field;

/**
 *
 * Created by jiangwj on 2015/1/31.
 */
public abstract class CustomCursorLoader extends CursorLoader {

    private final ContentObserver _observer;

    public CustomCursorLoader(Context context) {
        super(context);
        _observer = findObserver(this);
    }

    @Override
    public Cursor loadInBackground() {
        Cursor cursor = createCursor();
        if (cursor != null) {
            // Ensure the cursor window is filled
            cursor.getCount();
            cursor.registerContentObserver(getObserver());
        }
        return cursor;
    }

    protected abstract Cursor createCursor();

    protected ContentObserver getObserver() {
        return _observer;
    }

    private static ContentObserver findObserver(Object self) {
        try {
            Field field = CursorLoader.class.getDeclaredField("mObserver");
            field.setAccessible(true);
            return (ContentObserver) field.get(self);
        } catch (Exception ex) {
            // Ignore.
        }
        return null;
    }

}
